package router

import (
	"net/http"

	"github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/handlers"
	routes "github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/server/http/routes"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// New constructs the base gin engine with default middleware and routes.
func New(alertHandler *handlers.AlertHandler, ticketHandler *handlers.TicketHandler, aiHandler *handlers.AIHandler, authHandler *handlers.AuthHandler, analyticsHandler *handlers.AnalyticsHandler, knowledgeHandler *handlers.KnowledgeHandler, settingsHandler *handlers.SettingsHandler, integrationHandler *handlers.IntegrationHandler, jwtSecret string) *gin.Engine {
	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(gin.Logger())

	// CORS middleware
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	r.GET("/healthz", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})

	// Prometheus metrics endpoint
	r.GET("/metrics", gin.WrapH(promhttp.Handler()))

	routes.RegisterAPIRoutes(r.Group("/api"), alertHandler, ticketHandler, aiHandler, authHandler, analyticsHandler, knowledgeHandler, settingsHandler, integrationHandler, jwtSecret)

	return r
}
